const marked = require('marked')

const { writeBlog, findOne, find } = require('../models/article')

const article = async (req, res, next) => {
    res.set('content-type', 'application/json; charset=utf-8')
    const {a_author, a_title, a_avatar, a_content} = req.body
    const result = await writeBlog(a_author, a_avatar, a_title, a_content)
    if(result) {
        console.log(result)
        res.render('succ', {
            data: JSON.stringify({
                id: result._id
            })
        })
    }
}

const articleDetail = async (req, res, next) => {
    const id = req.params.id

    const blog = await findOne(id)

    if(blog) {
        const {username, avatar, title, content} = blog
        let html

        await marked(content, function (err, data) {
            if(err) throw err
            html = data
        })

        res.render('succ', {
            data: JSON.stringify({
                username: username,
                avatar: avatar,
                title: title,
                content: html,
            })
        })
    }

}

const articleList = async (req, res, next) => {

    const numPer = 5

    res.set('content-type', 'application/json; charset=utf-8')
    const num = req.params.num
    const blogs = await find()

    const ret_blogs = blogs.slice(num * numPer, (num + 1) * numPer)

    console.log(ret_blogs, num * numPer, )

    res.render('succ', {
        data: JSON.stringify(ret_blogs)
    })
}

module.exports = {
    article,
    articleDetail,
    articleList,
}